package com;

import java.io.FileOutputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class HttpConfiguration {
	private String password="admin";
	private static HttpConfiguration httpConfiguration=null;	
	
	private HttpConfiguration(){}
	
	public static HttpConfiguration Instance () {
        if (httpConfiguration == null) {
        	httpConfiguration = new HttpConfiguration();
        }
        return httpConfiguration;
    }	
	public List<Object> changeConfiguration(String s){		
		List<Object> list= new ArrayList<Object>();		
		String[] m = s.split("\\?");			
		if(m[0].equals("/Configuration")){
			String[] arrayConfig = m[1].split("&");
				for(String str: arrayConfig){
					String[] timeArray=str.split("=");
					list.add(timeArray[1]);				
				}			
				if((!((String)list.get(list.size()-1)).equals(this.password))){
					list.clear();
					return list;
				}
		}
		return list;
	}

	public boolean writeToXml(List<Object> list){
		if((list.isEmpty() || (list.size()>4) || (list.size()<3))){
			return false;
		}else{						
			try{
			 String newRootDirectory = URLDecoder.decode((String)list.get(0), "UTF-8");
				
	   		 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	   		 DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	   		 Document doc = dBuilder.newDocument();   			
   			
	   		 Element RootElement=doc.createElement("customization");		
	    		
	   		 Element NameElementTitle=doc.createElement("rootdirectory");
	   		 NameElementTitle.appendChild(doc.createTextNode(newRootDirectory));
	   		 RootElement.appendChild(NameElementTitle);		           
		        
		     Element NameElementCompile=doc.createElement("port");
		     NameElementCompile.appendChild(doc.createTextNode((String)list.get(1)));
		     RootElement.appendChild(NameElementCompile);
		        
		     Element NameElementRuns=doc.createElement("numberthread"); 
		     NameElementRuns.appendChild(doc.createTextNode((String)list.get(2)));
		     RootElement.appendChild(NameElementRuns);
		          
		     doc.appendChild(RootElement);
		         
		    Transformer t=TransformerFactory.newInstance().newTransformer();
	        t.transform(new DOMSource(doc), new StreamResult(new FileOutputStream(".\\config\\config.xml")));
		 	}catch(Exception e){
				System.out.println("Error to write config");
			}
			return true;
		}
	}
}
